package com.kylin.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.kylin.common.core.beans.GlobalResultCode;
import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.core.entity.Page;
import com.kylin.common.core.exception.ServiceException;
import com.kylin.common.core.validator.Assert;
import com.kylin.common.core.validator.BeanValidator;
import com.kylin.common.datascope.annotation.DataScope;
import com.kylin.common.log.annotation.Log;
import com.kylin.common.log.enums.BusinessType;
import com.kylin.common.poi.excel.EasyExcelUtil;
import com.kylin.common.poi.excel.handler.ExcelDictService;
import com.kylin.common.security.util.SecurityUtils;
import com.kylin.system.common.utils.PasswordGenerator;
import com.kylin.system.entity.SysDept;
import com.kylin.system.entity.SysPost;
import com.kylin.system.entity.SysRole;
import com.kylin.system.entity.SysUser;
import com.kylin.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author wuhao
 */

@Api(tags = "api接口测试")
@RestController
@RequestMapping("/user")
public class SysUserController
{
    /** 创建时间数据库字段 */
    private static final String CREATE_TIME_FILED = "t1.create_time";

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ExcelDictService excelDictService;
    @Autowired
    private SysDeptService deptService;


    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @DataScope(userAlias = "t1", deptAlias = "t1")
    public ResultBean<Page<SysUser>> list(SysUser user)
    {
        // 构造搜索
        user.getQueryWrapper()
                .apply("t1.dept_id = t2.id and t1.delete_flag = 1 and t2.delete_flag = 1")
                .like(StringUtils.isNotBlank(user.getUserName()), "t1.user_name", user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhone()),"t1.phone", user.getPhone())
                .eq(StringUtils.isNotBlank(user.getStatus()), "t1.status", user.getStatus())
                .like(StringUtils.isNotBlank(user.getNickName()), "t1.nick_name", user.getNickName())
                //.ge(StringUtils.isNotEmpty(user.getBeginTime()),CREATE_TIME_FILED, DateTimeUtils.parseDate(user.getBeginTime()))
                //.le(StringUtils.isNotEmpty(user.getEndTime()), CREATE_TIME_FILED, DateTimeUtils.parseDate(user.getEndTime()))
                .and(ObjectUtils.isNotEmpty(user.getDeptId()),
                        i-> i.eq("t1.dept_id", user.getDeptId())
                                .or()
                                .apply("t1.dept_id in (select d.id from sys_dept d where d.parent_ids like '%"+user.getDeptId()+",%')"));
        Page<SysUser> page = new Page<>();
        page = userService.listPage(page, user);
        return ResultBean.onSuccess(page);
    }

    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/{userId}" })
    public ResultBean<SysUser> getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
//        List<SysRole> roles = roleService.list(new SysRole());
//
//        Map<String, Object> data = new HashMap<>();
//        data.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
//        data.put("posts", postService.list(new SysPost()));


//        if(ObjectUtils.isNotEmpty(userId)) {
            SysUser user = userService.getById(userId);
            user.setRoleIds(roleService.selectRoleListByUserId(userId));
//            data.put("user", user);
//            data.put("roleIds", roleService.selectRoleListByUserId(userId));
//            data.put("postIds", postService.selectPostListByUserId(userId));
//        }
        return ResultBean.onSuccess(user);
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultBean<Object> add(@RequestBody SysUser user)
    {
        // 参数校验
        BeanValidator.validate(user);
        user.setPassword(SecurityUtils.encryptPassword(StringUtils.isNotBlank(user.getPassword())? user.getPassword(): "User@123"));
        userService.insertUser(user);
        return ResultBean.onSuccess();
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultBean<Object> edit(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        // 参数校验
        BeanValidator.validate(user);
        userService.updateUser(user);
        return ResultBean.onSuccess();
    }

    /**
     * 删除用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ResultBean<Object> remove(@PathVariable Long[] userIds)
    {
        Assert.isBlank("请选择需要删除的数据", userIds);
        userService.deleteUserByIds(userIds);
        return ResultBean.onSuccess();
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResultBean<Object> changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.updateStatus(user.getId(), user.getStatus());
        return ResultBean.onSuccess();
    }


    /**
     * 获取用户信息
     */
    @GetMapping("getInfo")
    public ResultBean<Object> getInfo()
    {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);

        SysUser user = userService.getById(userId);
        if(user == null) {
            throw new ServiceException("用户不存在");
        }

        JSONObject result = JSON.parseObject(JSON.toJSONString(user));
        result.put("roles", roles);
        result.put("permissions", permissions);

        // 获取用户部门
        SysDept dept = deptService.getById(user.getDeptId());
        result.put("deptName", dept.getDeptName());

        return ResultBean.onSuccess(result);
    }

    /**
     * 获取当前用户信息
     */
//    @GetMapping("/info/{username}")
//    public ResultBean<UserInfo> info(@PathVariable("username") String username)
//    {
//        SysUser sysUser = userService.selectUserByUserName(username);
//        if (ObjectUtils.isEmpty(sysUser))
//        {
//            throw new ServiceException("用户名或密码错误");
//        }
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(sysUser.getId());
//        // 权限集合
//        Set<String> permissions = permissionService.getMenuPermission(sysUser.getId());
//        UserInfo sysUserVo = new UserInfo();
//        sysUserVo.setSysUser(sysUser);
//        sysUserVo.setRoles(roles);
//        sysUserVo.setPermissions(permissions);
//        return ResultBean.onSuccess(sysUserVo);
//    }

    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public ResultBean<Object> resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.resetUserPwd(user.getId(), user.getPassword());

        return ResultBean.onSuccess();
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPassword")
    public ResultBean<Object> resetPwdNew(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        String newPassword = PasswordGenerator.generatePassword(12);
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        userService.resetUserPwd(user.getId(), user.getPassword());

        Map<String, String> res = new HashMap<>();
        res.put("password", newPassword);
        return ResultBean.onSuccess(res);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException
    {
        // 构造搜索
        user.getQueryWrapper()
                .apply("t1.dept_id = t2.id and t1.delete_flag = 1 and t2.delete_flag = 1")
                .like(StringUtils.isNotBlank(user.getUserName()), "t1.user_name", user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhone()),"t1.phone", user.getPhone())
                .eq(StringUtils.isNotBlank(user.getStatus()), "t1.status", user.getStatus())
                .and(ObjectUtils.isNotEmpty(user.getDeptId()),
                        i-> i.eq("t1.dept_id", user.getDeptId())
                                .or()
                                .apply("t1.dept_id in (select d.id from sys_dept d where d.parent_ids like '%"+user.getDeptId()+",%')"));
        List<SysUser> list = userService.list(user);
        EasyExcelUtil.exportExcel(list, "用户数据汇总", "用户数据", SysUser.class, "用户数据导出", response);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public ResultBean<Object> importData(MultipartFile file, boolean updateSupport)
    {
        String message = "";
        try {
            List<SysUser> list = EasyExcelUtil.importExcel(file, 1, 1,true, SysUser.class);
            message = userService.importUser(list, updateSupport, SecurityUtils.getUserId());
        } catch (Exception e) {
            return ResultBean.onFail("导入失败，请检查格式是否正确！");
        }
        return new ResultBean<>(GlobalResultCode.SUCCESS.getCode(), message);

    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        List<SysUser> list = new ArrayList<>();
        list.add(new SysUser());
        EasyExcelUtil.exportExcel(list, "用户数据汇总", "用户数据", SysUser.class, "用户数据导入模板", response);
    }
}
